﻿using DotNetCore.CAP;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Threading.Tasks;
using X23.Application.ExcelManagement;
using X23.Application.UserManagement;
using X23.Application.UserManagement.Dto;
using X23.Extensions.AttributeExtensions;
using X23.Model.User;
using X23.Util.LinqUtil;

namespace X23.Controllers
{
    /// <summary>
    /// 用户管理
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class FileController : BaseApiController
    {
        private readonly ICapPublisher _capPublisher;
        private readonly IExcelManagementService _excelManagementService;
        private readonly IWebHostEnvironment _webHostEnvironment;

        public FileController(
            ICapPublisher capPublisher,
            IExcelManagementService excelManagementService,
            IWebHostEnvironment webHostEnvironment
            )
        {
            _capPublisher = capPublisher;
            _excelManagementService = excelManagementService;
            _webHostEnvironment = webHostEnvironment;
        }
        /// <summary>
        /// 获取文件(暂时是excel) TODO
        /// </summary>
        /// <param name="taskPerformanceId"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<FileResult> GetExportFile(int taskPerformanceId)
        {
            var taskPerformance = await _excelManagementService.GetTaskPerformance(taskPerformanceId);
            var fileStream = _excelManagementService.DownFileStream(taskPerformance.Guid, taskPerformance.FileType);
            return File(fileStream.ToArray(), "application/vnd.ms-excel", taskPerformance.FileName);
        }


        /// <summary>
        /// 批量上传文件
        /// </summary>
        /// <param name="formCollection"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<List<int>> UploadPostFile(IFormCollection formCollection)
        {
            var result = new List<int>();
            FormFileCollection fileCollection = (FormFileCollection)formCollection.Files;
            foreach (IFormFile file in fileCollection)
            {
                bool isSuccess = true;
                var fileName = "";
                var guid = Guid.NewGuid().ToString("N");
                var tail = "";
                try
                {
                    StreamReader reader = new StreamReader(file.OpenReadStream());
                    string content = reader.ReadToEnd();
                    fileName = file.FileName;
                    tail = fileName.Substring(fileName.LastIndexOf(@".") + 1);
                    string path = Path.Combine(_webHostEnvironment.ContentRootPath, "File", guid + "." + tail);
                    if (System.IO.File.Exists(path))
                    {
                        System.IO.File.Delete(path);
                    }
                    using (FileStream fs = System.IO.File.Create(path))
                    {
                        file.CopyTo(fs);
                        fs.Flush();
                    }
                }
                catch (Exception)
                {
                    isSuccess = false;
                    //todo 记录日志
                }
                finally
                {
                    var insert = await _excelManagementService.AddTaskPerformance(new Application.ExcelManagement.Dto.TaskPerformanceDto
                    {
                        TaskExeStatus = isSuccess ? Model.Const.Enum.TaskExeStatus.Success : Model.Const.Enum.TaskExeStatus.Fail,
                        Code = "File",
                        Guid = guid,
                        FileType = tail,
                        FileName = fileName
                    });
                    result.Add(insert.Id);
                }
            }
            return result;
        }
    }
}
